//
//  ViewController.m
//  CoreBluetoothDemo
//
//  Created by administrator on 2018/6/11.
//  Copyright © 2018年 administrator. All rights reserved.
//

#import "ViewController.h"
#import  <CoreBluetooth/CoreBluetooth.h>

@interface ViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate>
/*中心角色*/
@property (nonatomic, strong) CBCentralManager *mgr;
/*外设角色，我们当选中某个外设连接成功后，将外设对象赋值给该对象*/
@property (nonatomic, strong) CBPeripheral *peripheral;
@property(nonatomic,strong)CBCharacteristic *writestic;
@property(nonatomic,strong)CBCharacteristic *readstic;
@property (weak, nonatomic) IBOutlet UITextView *textView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}
- (IBAction)connect:(id)sender {
    NSLog(@"----开始扫描---");
    [self searchDevcie];
}
- (IBAction)sendData:(id)sender {
    NSLog(@"----发送数据---");
    NSData *data =[@"testdata" dataUsingEncoding:NSUTF8StringEncoding];
    if (self.writestic) {
        [self.peripheral writeValue:data  forCharacteristic:self.writestic    type:CBCharacteristicWriteWithoutResponse];
    }
    
    
}


//扫描
- (void)searchDevcie{
    if(_mgr!=nil&& _mgr.state==5){
        [self.mgr scanForPeripheralsWithServices:nil options:nil];
    }
}
//扫描到设备后
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(nonnull CBPeripheral *)peripheral advertisementData:(nonnull NSDictionary<NSString *,id> *)advertisementData RSSI:(nonnull NSNumber *)RSSI
{
     NSLog(@"扫描设备---%@",peripheral.name);
    if ([peripheral.name isEqualToString:@"administrator的MacBook Pro"]) {
        self.peripheral = peripheral;
        self.peripheral.delegate = self;
         [self.mgr stopScan];
        [self connectDevice:peripheral];
    }
}

//从设备列表选中我们要的设备  连接设备
- (void)connectDevice:(CBPeripheral *)peripheral{
    [self.mgr connectPeripheral:peripheral options:nil];
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case 0:
            NSLog(@"CBCentralManagerStateUnknown");//设备类型位置
            break;
        case 1:
            NSLog(@"CBCentralManagerStateResetting");//设备初始化中
            break;
        case 2:
            NSLog(@"CBCentralManagerStateUnsupported");//不支持蓝牙
            break;
        case 3:
            NSLog(@"CBCentralManagerStateUnauthorized");//设备未授权
            break;
        case 4:
        {
            NSLog(@"CBCentralManagerStatePoweredOff");//蓝牙未开启
        }
            break;
        case 5:
        {
            NSLog(@"CBCentralManagerStatePoweredOn");//蓝牙已开始
            //如果想自动扫描，在此处开始扫描即可
        }
            break;
        default:
            break;
    }
}
// 中心管理者连接外设成功(如果外设成功与中心设备连接成功之后会自动触发该方法)
- (void)centralManager:(CBCentralManager *)central // 中心管理者
  didConnectPeripheral:(CBPeripheral *)peripheral // 外设
{
    NSLog(@"-hy----连接成功");
    // 标记我们的外设,让他的生命周期 = ViewController
    //  设置外设的代理
    
    // 外设发现服务,传nil代表不过滤
    //调用该方法后，将会自动调用didDiscoverServices()代理方法，用于发现服务
    [self.peripheral discoverServices:nil];
    //既然连接上了，为了解决性能，就停止扫描吧
   
}
// 外设连接失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"-hy------连接失败");
}
// 丢失连接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"-hy------断开连接");
}


- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    NSLog(@"-hy------didDiscoverServices");
    if (error)
    {
        NSLog(@"-hy------Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
        return;
    }
    //服务并不是我们的目标，也没有实际意义。我们需要用的是服务下的特征，查询（每一个服务下的若干）特征
    for (CBService *service in peripheral.services)
    {
        //好，发现了服务 接下来就是最重要的特征了
        //调用该方法后，当发现了service服务中的特征后，将会自动触发didDiscoverCharacteristicsForService()方法
        [peripheral discoverCharacteristics:nil forService:service];
    }
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    NSLog(@"-hy----didDiscoverCharacteristicsForService");
    if (error)
    {
        NSLog(@"----error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
        return;
    }
    for (CBCharacteristic *characteristic in service.characteristics){
        [peripheral readValueForCharacteristic:characteristic]; // 外设读取特征的值
    }
    for (CBCharacteristic *characteristic in service.characteristics){
        [peripheral discoverDescriptorsForCharacteristic:characteristic]; // 外设发现特征的描述
    }
    
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
{
    for (CBDescriptor *descriptor in characteristic.descriptors) {
        NSLog(@"----HY---descriptor.UUID:%@",descriptor.UUID.UUIDString);
    }
}

// 更新特征的value的时候会调用 （凡是从蓝牙传过来的数据都要经过这个回调，简单的说这个方法就是你拿数据的唯一方法） 你可以判断是否
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    for (CBDescriptor *descriptor in characteristic.descriptors) {
        NSLog(@"descriptor.UUID:%@",descriptor.UUID);
    }
    
    if (characteristic ==  self.readstic) {
        //characteristic.value 就是我们想要的数据了
        NSLog(@"----获取到蓝牙数据---%zd",characteristic.value.length);
        
        NSString *result = [[NSString alloc] initWithData:characteristic.value  encoding:NSUTF8StringEncoding];
        self.textView.text = [NSString stringWithFormat:@"%@\r\n%@",self.textView.text,result];

    }
}

@end





























